<template>
  <div class="buy-gift-page min-h-screen bg-gradient-to-br from-blue-50 via-cyan-50 to-blue-100">
    <!-- Hero Section -->
    <div class="relative overflow-hidden bg-gradient-to-r from-blue-600 via-cyan-600 to-blue-700">
      <div class="absolute inset-0">
        <div class="absolute inset-0 bg-black opacity-20"></div>
        <div class="absolute top-0 left-0 w-full h-full">
          <div class="absolute top-10 left-10 w-32 h-32 bg-white bg-opacity-10 rounded-full animate-pulse"></div>
          <div class="absolute top-20 right-20 w-24 h-24 bg-white bg-opacity-10 rounded-full animate-pulse delay-1000"></div>
          <div class="absolute bottom-10 left-1/3 w-40 h-40 bg-white bg-opacity-10 rounded-full animate-pulse delay-2000"></div>
        </div>
      </div>
      
      <div class="relative container mx-auto px-4 py-16">
        <div class="text-center text-white">
          <h1 class="text-5xl font-bold mb-4 animate-fade-in">
            <span class="bg-gradient-to-r from-yellow-300 to-cyan-300 bg-clip-text text-transparent">
              买赠活动
            </span>
          </h1>
          <p class="text-xl mb-8 opacity-90 animate-fade-in-delay">购买指定商品，免费获得超值赠品</p>
          <div class="flex justify-center space-x-8 text-sm">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-yellow-400 rounded-full mr-2 animate-ping"></div>
              <span>买就送</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-cyan-400 rounded-full mr-2 animate-ping delay-500"></div>
              <span>超值赠品</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-blue-400 rounded-full mr-2 animate-ping delay-1000"></div>
              <span>限时活动</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="container mx-auto px-4 py-8">
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <el-skeleton :rows="5" animated />
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="container mx-auto px-4 py-8">
      <div class="bg-white rounded-2xl shadow-lg p-6 text-center">
        <el-icon size="48" class="text-gray-400 mb-4"><Warning /></el-icon>
        <p class="text-gray-600 mb-4">{{ error }}</p>
        <el-button type="primary" @click="fetchPromotions">重新加载</el-button>
      </div>
    </div>

    <!-- Content -->
    <div v-else class="container mx-auto px-4 py-8">
      <!-- Buy Gift Activities -->
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-6">买赠活动</h3>
        
                 <div v-if="buyGiftItems.length === 0" class="text-center py-12">
           <el-icon size="64" class="text-gray-300 mb-4"><Present /></el-icon>
           <p class="text-gray-500 text-lg">暂无买赠活动</p>
           <p class="text-gray-400 text-sm mt-2">敬请期待更多买赠优惠</p>
         </div>

        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
            v-for="item in buyGiftItems"
            :key="item.id"
            class="bg-gradient-to-br from-blue-50 to-cyan-50 rounded-xl overflow-hidden border border-blue-200 hover:shadow-lg transition-all duration-300"
          >
            <!-- Activity Header -->
            <div class="bg-gradient-to-r from-blue-500 to-cyan-500 p-4 text-white">
              <div class="flex items-center justify-between">
                <h4 class="font-bold text-lg">买赠优惠</h4>
                <div class="bg-white bg-opacity-20 px-2 py-1 rounded-full text-xs font-bold">
                  {{ getItemStatus(item) }}
                </div>
              </div>
            </div>

            <!-- Main Product -->
            <div class="mb-4">
              <div class="p-4 bg-white rounded-lg border border-blue-100 hover:shadow-md transition-shadow duration-300">
                <!-- 商品名称和标签 -->
                <div class="flex items-start gap-3">
                  <img
                    :src="getImageSrc(item.goodsInfo.mainPic)"
                    :alt="item.goodsInfo.title"
                    class="w-16 h-16 object-cover rounded-lg shadow-sm flex-shrink-0"
                    @error="handleImgError"
                  />
                  <div class="flex-1 min-w-0">
                    <h4 class="text-base font-medium text-gray-900 mb-1 line-clamp-2">{{ item.goodsInfo.title }}</h4>
                    <p class="text-xs text-gray-600 mb-2">{{ item.goodsInfo.manufacturer }}</p>
                    <div class="flex flex-wrap gap-1 mb-2">
                      <el-tag size="small" class="!text-xs !px-2 !py-1 !bg-blue-50 !border-blue-100 !text-blue-700">{{ item.goodsInfo.goodsSpec }}</el-tag>
                      <el-tag size="small" class="!text-xs !px-2 !py-1 !bg-gray-50 !border-gray-100 !text-gray-700">{{ item.goodsInfo.qCategory }}</el-tag>
                    </div>
                    
                    <!-- 近效期信息 -->
                    <div v-if="item.goodsInfo.nearestExpiredDate" class="mb-2">
                      <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-500">有效期:</span>
                        <span class="text-xs text-orange-600 font-medium">{{ formatDate(item.goodsInfo.nearestExpiredDate) }}</span>
                      </div>
                    </div>
                    
                    <!-- 价格信息 -->
                    <div class="flex items-center justify-between">
                      <div class="flex items-baseline gap-1">
                        <span class="text-sm font-semibold text-blue-600">¥{{ calculateDiscountedPrice(Number(item.taxprice), item.goodsInfo.noDiscounts) }}</span>
                        <span v-if="userStore.userInfo?.discount !== 1" class="text-xs text-gray-400 line-through">¥{{ Number(item.taxprice).toFixed(2) }}</span>
                      </div>
                      <span class="px-2 py-1 bg-blue-50 text-blue-700 rounded-full text-xs font-medium">
                        {{ Number(item.num) }}{{ item.goodsInfo.unit }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Gift Product -->
            <div class="mb-4">
              <div class="p-4 bg-gradient-to-r from-orange-50/50 to-yellow-50/50 rounded-lg border border-orange-100 hover:shadow-md transition-shadow duration-300">
                <!-- 商品名称和标签 -->
                <div class="flex items-start gap-3">
                  <div class="relative" v-if="item.freeGoodsInfo && item.freeGoodsInfo.id">
                    <img
                      :src="getImageSrc(item.freeGoodsInfo.mainPic)"
                      :alt="item.freeGoodsInfo.title"
                      class="w-16 h-16 object-cover rounded-lg shadow-sm flex-shrink-0"
                      @error="handleImgError"
                    />
                    <div class="absolute -top-1 -right-1 bg-red-500 text-white text-xs px-1 py-0.5 rounded-full">赠</div>
                  </div>
                  <div class="flex-1 min-w-0" v-if="item.freeGoodsInfo && item.freeGoodsInfo.id">
                    <h4 class="text-base font-medium text-gray-900 mb-1 line-clamp-2">{{ item.freeGoodsInfo.title }}</h4>
                    <p class="text-xs text-gray-600 mb-2">{{ item.freeGoodsInfo.manufacturer }}</p>
                    <div class="flex flex-wrap gap-1 mb-2">
                      <el-tag size="small" class="!text-xs !px-2 !py-1 !bg-orange-50 !border-orange-100 !text-orange-700">{{ item.freeGoodsInfo.goodsSpec }}</el-tag>
                      <el-tag size="small" class="!text-xs !px-2 !py-1 !bg-gray-50 !border-gray-100 !text-gray-700">{{ item.freeGoodsInfo.qCategory }}</el-tag>
                    </div>
                    
                    <!-- 近效期信息 -->
                    <div v-if="item.freeGoodsInfo.nearestExpiredDate" class="mb-2">
                      <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-500">有效期:</span>
                        <span class="text-xs text-orange-600 font-medium">{{ formatDate(item.freeGoodsInfo.nearestExpiredDate) }}</span>
                        <el-tag
                          v-if="isNearExpiry(item.freeGoodsInfo.nearestExpiredDate)"
                          size="small"
                          type="danger"
                          effect="plain"
                          class="!text-xs"
                        >
                          近效期
                        </el-tag>
                      </div>
                    </div>
                    
                    <!-- 价格信息 -->
                    <div class="flex items-center justify-between">
                      <div class="flex items-baseline gap-1">
                        <span class="text-sm font-semibold text-orange-600">¥{{ calculateDiscountedPrice(Number(item.freeTaxPrice), item.goodsInfo.noDiscounts) }}</span>
                        <span v-if="userStore.userInfo?.discount !== 1" class="text-xs text-gray-400 line-through">¥{{ Number(item.freeTaxPrice).toFixed(2) }}</span>
                      </div>
                      <span class="px-2 py-1 bg-orange-50 text-orange-700 rounded-full text-xs font-medium">
                        {{ Number(item.freeNum) }}{{ item.freeGoodsInfo.unit }}
                      </span>
                    </div>
                  </div>
                  <div v-else class="flex-1 min-h-[128px] flex items-center">
                    <div>
                      <h4 class="text-base font-medium text-gray-900 mb-1 line-clamp-2">{{ item.remark || '赠品信息待更新' }}</h4>
                      <p class="text-xs text-gray-500">赠品详情请咨询客服</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Activity Time -->
            <div v-if="item.promotion" class="px-4 py-1.5 bg-gray-50 border-t border-gray-100">
              <div class="text-xs text-gray-500 text-center">
                {{ formatDate(item.promotion.startTime) }} - {{ formatDate(item.promotion.endTime) }}
              </div>
            </div>

            <!-- Action Button -->
            <button
              @click="createBuyGiftOrder(item)"
              :disabled="!isItemActive(item) || isCreatingBuyGiftOrder"
              class="w-full py-2.5 rounded-lg font-medium text-sm transition-all duration-200 shadow-sm"
              :class="isItemActive(item) && !isCreatingBuyGiftOrder
                ? 'bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white shadow-blue-100' 
                : 'bg-gray-100 text-gray-400 cursor-not-allowed'"
            >
              {{ isItemActive(item) 
                ? (isCreatingBuyGiftOrder ? '购买中...' : getButtonText(item))
                : getButtonText(item) }}
            </button>
          </div>
        </div>
      </div>

      <!-- How it works -->
      <div class="bg-white rounded-2xl shadow-lg p-6 mt-8">
        <h3 class="text-xl font-bold text-gray-800 mb-6">买赠活动说明</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="text-center">
            <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon size="24" class="text-blue-600"><ShoppingCart /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">选择商品</h4>
            <p class="text-sm text-gray-600">选择参与买赠活动的指定商品和数量</p>
          </div>
                     <div class="text-center">
             <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
               <el-icon size="24" class="text-blue-600"><Present /></el-icon>
             </div>
             <h4 class="font-semibold text-gray-800 mb-2">获得赠品</h4>
             <p class="text-sm text-gray-600">购买后自动获得对应的免费赠品</p>
           </div>
          <div class="text-center">
            <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <el-icon size="24" class="text-blue-600"><Check /></el-icon>
            </div>
            <h4 class="font-semibold text-gray-800 mb-2">直接下单</h4>
            <p class="text-sm text-gray-600">跳过购物车，直接生成订单，享受双重价值</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning, Present, ShoppingCart, Check } from '@element-plus/icons-vue'
import { promotionApi } from '@/api'
import type { BuyGiftPromotion, BuyGiftDetail } from '@/api/modules/promotion'
import { handleImageError as handleImgError, getImageSrc } from '@/lib/imageUtils'
import { useUserStore } from '@/stores/user'
// Extended BuyGiftDetail with promotion info
interface ExtendedBuyGiftDetail extends BuyGiftDetail {
  promotion?: BuyGiftPromotion
}

const router = useRouter()
const userStore = useUserStore()
const loading = ref(true)
const error = ref('')
const promotions = ref<BuyGiftPromotion[]>([])
const buyGiftItems = ref<ExtendedBuyGiftDetail[]>([])

// 计算用户折扣后的价格
function calculateDiscountedPrice(price: number, noDiscounts: number): number {
  const discount = userStore.userInfo?.discount || 1
  if (noDiscounts === 1) {
    return Number(price.toFixed(2))
  }
  return Number((price * discount).toFixed(2))
}

// 计算商品总价（考虑数量和折扣）
function calculateTotalPrice(price: number, quantity: number, noDiscounts: number): number {
  const discountedPrice = calculateDiscountedPrice(price, noDiscounts)
  return Number((discountedPrice * quantity).toFixed(2))
}

// Methods
async function fetchPromotions() {
  try {
    loading.value = true
    error.value = ''
    
    const response = await promotionApi.getPromotionsByType('MZ')
    
    // response is ApiResponse<Promotion[]> due to response interceptor
    if (response.code === 1000 && response.data) {
      // Filter by Chinese promType or English promType
      promotions.value = (response.data || []).filter((p: any) => 
        p.promType === 'MZ' || p.promType === '买赠'
      ) as BuyGiftPromotion[]
      
      // Extract all buy-gift items from non-ended promotions
      buyGiftItems.value = []
      promotions.value.forEach(promotion => {
        // Show items from promotions that are not ended (including not started and active)
        if (!isPromotionEnded(promotion)) {
          buyGiftItems.value.push(...promotion.details.map(detail => ({
            ...detail,
            promotion: promotion
          })))
        }
      })
    } else {
      throw new Error(response.message || '获取买赠活动失败')
    }
  } catch (err: any) {
    error.value = err.message || '网络错误，请稍后重试'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

function isPromotionActive(promotion: BuyGiftPromotion): boolean {
  const now = new Date()
  const startTime = new Date(promotion.startTime)
  const endTime = new Date(promotion.endTime)
  
  return promotion.status === 1 && now >= startTime && now <= endTime
}

function isPromotionEnded(promotion: BuyGiftPromotion): boolean {
  const now = new Date()
  const endTime = new Date(promotion.endTime)
  
  return promotion.status === 0 || now > endTime
}

function isItemActive(item: ExtendedBuyGiftDetail): boolean {
  if (!item.promotion) return item.status === 1
  return item.status === 1 && isPromotionActive(item.promotion)
}

function getItemStatus(item: ExtendedBuyGiftDetail): string {
  if (!item.promotion) return item.status === 1 ? '进行中' : '已停用'
  
  const now = new Date()
  const startTime = new Date(item.promotion.startTime)
  const endTime = new Date(item.promotion.endTime)
  
  if (item.promotion.status === 0 || item.status === 0) return '已停用'
  if (now < startTime) return '未开始'
  if (now > endTime) return '已结束'
  return '进行中'
}

function getButtonText(item: ExtendedBuyGiftDetail): string {
  if (!item.promotion) return item.status === 1 ? '立即购买' : '已停用'
  
  const now = new Date()
  const startTime = new Date(item.promotion.startTime)
  const endTime = new Date(item.promotion.endTime)
  
  if (item.promotion.status === 0 || item.status === 0) return '已停用'
  if (now < startTime) return '未开始'
  if (now > endTime) return '已结束'
  return '立即购买'
}

function formatDate(dateString: string): string {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 判断近效期是否小于180天
function isNearExpiry(dateString: string | null): boolean {
  if (!dateString) return false

  try {
    const expiryDate = new Date(dateString)
    const today = new Date()

    // 计算距离过期还有多少天
    const diffTime = expiryDate.getTime() - today.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    // 如果距离过期小于等于180天，则标记为近效期
    return diffDays <= 180 && diffDays >= 0
  } catch (error) {
    return false
  }
}

// 买赠订单创建状态
const isCreatingBuyGiftOrder = ref(false)

async function createBuyGiftOrder(item: ExtendedBuyGiftDetail) {
  if (!isItemActive(item)) {
    const status = getItemStatus(item)
    ElMessage.warning(`活动${status}`)
    return
  }
  
  if (!item.promotion) {
    ElMessage.error('找不到对应的促销活动')
    return
  }
  
  if (isCreatingBuyGiftOrder.value) {
    return
  }
  
  isCreatingBuyGiftOrder.value = true
  
  const quantity = item.num
  const discountedPrice = calculateDiscountedPrice(Number(item.taxprice), item.goodsInfo.noDiscounts)
  const totalPrice = calculateTotalPrice(Number(item.taxprice), Number(quantity), item.goodsInfo.noDiscounts)
  
  try {
    // 构建确认信息
    let confirmMessage = `确认购买 ${item.goodsInfo.title} ${Number(quantity)}吗？\n折后单价：¥${discountedPrice}\n总价：¥${totalPrice}`;
    
    // 添加赠品信息
    if (item.freeGoodsInfo && item.freeGoodsInfo.id) {
      confirmMessage += `\n赠送商品：${item.freeGoodsInfo.title} ${Number(item.freeNum)}`;
    } else {
      confirmMessage += `\n赠送：${item.remark || '赠品信息待更新'}`;
    }
    
    // 确认对话框
    await ElMessageBox.confirm(
      confirmMessage,
      '确认购买',
      {
        confirmButtonText: '确认购买',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 构建备注信息
    let remark = `买赠订单：购买 ${item.goodsInfo.title}`;
    if (item.freeGoodsInfo && item.freeGoodsInfo.id) {
      remark += `，赠送 ${item.freeGoodsInfo.title}`;
    } else {
      remark += `，${item.remark || '赠品信息待更新'}`;
    }
    
    const response = await promotionApi.createBuyGiftOrder({
      billNo: item.promotion.billNo,
      goodsId: item.goodsId,
      quantity: quantity,
      remark: remark
    })
    
    if (response.code === 1000) {
      ElMessage.success(`买赠订单创建成功！订单号：${response.data.orderNum}`)
      // Navigate to my orders page
      router.push('/my-orders')
    } else {
      throw new Error(response.message || '创建订单失败')
    }
  } catch (error: any) {
    if (error === 'cancel') {
      // 用户取消，不显示错误信息
      return
    }
    ElMessage.error(error.message || '创建订单失败，请重试')
  } finally {
    isCreatingBuyGiftOrder.value = false
  }
}

// Lifecycle
onMounted(() => {
  fetchPromotions()
})
</script>

<style scoped>
@keyframes fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fade-in-delay {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 1s ease-out;
}

.animate-fade-in-delay {
  animation: fade-in-delay 1s ease-out 0.3s both;
}
</style> 